<?php

use App\Models\User;
use Illuminate\Support\Facades\Auth;

/**
 * 当前访问用户
 *
 * @return User|null 用户模型
 */
function user(): ?User
{
    return Auth::check() ? Auth::user() : null;
}

/**
 * 是否是超级管理员
 */
function isSuperAdmin(): bool
{
    return user() ? user()->is_super_admin : false;
}

/**
 * 权限判断
 * @param string $name
 * @param User|null $user
 * @param boolean $force
 * @return boolean
 */
function access(string $name, ?User $user = null, bool $force = false): bool
{
    $user = $user ?? user();

    if (!$user) {
        abort(403);
    }

    if ($user->is_super_admin) {
        return true;
    }

    $state = $user->roles()->whereRelation('permissions', fn($query) => $query->where('name', $name))->exists();

    return $state === false && $force ? abort(403) : $state;
}

function getTree($data, $parent_id = 0)
{
    $tree = [];
    foreach ($data as $k => $v) {
        if ($v['parent_id'] == $parent_id) {
            $v['children'] = getTree($data, $v['id']);
            if (empty($v['children'])) unset($v['children']);
            $tree[] = $v;
            unset($data[$k]);
        }
    }
    return $tree;
}
